package com.how2java.tmall.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import com.github.pagehelper.PageHelper;
import com.how2java.tmall.comparator.ProductAllComparator;
import com.how2java.tmall.comparator.ProductDateComparator;
import com.how2java.tmall.comparator.ProductPriceComparator;
import com.how2java.tmall.comparator.ProductReviewComparator;
import com.how2java.tmall.comparator.ProductSaleCountComparator;
import com.how2java.tmall.pojo.Category;
import com.how2java.tmall.pojo.Order;
import com.how2java.tmall.pojo.Orderitem;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.pojo.Productimage;
import com.how2java.tmall.pojo.Propertyvalue;
import com.how2java.tmall.pojo.Review;
import com.how2java.tmall.pojo.User;
import com.how2java.tmall.service.CategoryService;
import com.how2java.tmall.service.OrderItemService;
import com.how2java.tmall.service.OrderService;
import com.how2java.tmall.service.ProductImageService;
import com.how2java.tmall.service.ProductService;
import com.how2java.tmall.service.PropertyValueService;
import com.how2java.tmall.service.ReviewService;
import com.how2java.tmall.service.UserService;

@Controller
public class ForeController {
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;
	@Autowired
	private UserService userService;
	@Autowired
	private ProductImageService productImageService;
	@Autowired
	private PropertyValueService propertyValueService;
	@Autowired
	private ReviewService reviewService;
	@Autowired
	private OrderItemService orderItemService;
	@Autowired
	private OrderService orderService;
	
	@RequestMapping("forehome")
    public String home(Model model) {
        List<Category> cs= categoryService.list();
        productService.fill(cs);
        productService.fillByRow(cs);
         model.addAttribute("cs", cs);
        return "fore/home";
    }
	
	@RequestMapping("foreregister")
	 public String register(Model model,User user) {
	     String name =  user.getName();
	     name = HtmlUtils.htmlEscape(name);
	     user.setName(name);
	     boolean exist = userService.isExist(name);
	      
	     if(exist){
	         String m ="用户名已经被使用,不能使用";
	         model.addAttribute("msg", m);
	         model.addAttribute("user", null);
	         return "fore/register";
	     }
	     userService.add(user);
	 
	     return "redirect:registerSuccessPage";
	 }
	
	@RequestMapping("forelogin")
    public String login(String name,String password, Model model, HttpSession session) {
        name = HtmlUtils.htmlEscape(name);
        User user = userService.get(name,password);
 
        if(null==user){
            model.addAttribute("msg", "账号密码错误");
            return "fore/login";
        }
        session.setAttribute("user", user);
        return "redirect:forehome";
    }
	
	@RequestMapping("forelogout")
    public String logout( HttpSession session) {
        session.removeAttribute("user");
        return "redirect:forehome";
    }
	
	@RequestMapping("foreproduct")
    public String product( int pid, Model model) {
        Product p = productService.get(pid);
 
        List<Productimage> productSingleImages = productImageService.list(p.getId(), ProductImageService.type_single);
        List<Productimage> productDetailImages = productImageService.list(p.getId(), ProductImageService.type_detail);
        p.setProductSingleImages(productSingleImages);
        p.setProductDetailImages(productDetailImages);
 
        List<Propertyvalue> pvs = propertyValueService.list(p.getId());
        List<Review> reviews = reviewService.list(p.getId());
        productService.setSaleAndReviewNumber(p);
        model.addAttribute("reviews", reviews);
        model.addAttribute("p", p);
        model.addAttribute("pvs", pvs);
        return "fore/product";
    }
 
	
	
	@RequestMapping("forecheckLogin")
    @ResponseBody
    public String checkLogin( HttpSession session) {
        User user =(User)  session.getAttribute("user");
        if(null!=user)
            return "success";
        return "fail";
    }
	
	
	@RequestMapping("foreloginAjax")
    @ResponseBody
    public String loginAjax(String name,String password,HttpSession session) {
        name = HtmlUtils.htmlEscape(name);
        User user = userService.get(name,password);
 
        if(null==user){
            return "fail";
        }
        session.setAttribute("user", user);
        return "success";
    }
	
	/**
	 * 分类页面  排序
	 * @param cid
	 * @param sort
	 * @param model
	 * @return
	 */
	@RequestMapping("forecategory")
    public String category(int cid,String sort, Model model) {
        Category c = categoryService.get(cid);
        productService.fill(c);
        productService.setSaleAndReviewNumber(c.getProducts());
 
        if(null!=sort){
            switch(sort){
                case "review":
                	/*按评论排序*/
                    Collections.sort(c.getProducts(),new ProductReviewComparator());
                    break;
                case "date" :
                	/*按照创建日期*/
                    Collections.sort(c.getProducts(),new ProductDateComparator());
                    break;
 
                case "saleCount" :
                	/*按照销量排序*/
                    Collections.sort(c.getProducts(),new ProductSaleCountComparator());
                    break;
 
                case "price":
                	/*按照销售价排序*/
                    Collections.sort(c.getProducts(),new ProductPriceComparator());
                    break;
 
                case "all":
                	/*综合考虑*/
                    Collections.sort(c.getProducts(),new ProductAllComparator());
                    break;
            }
        }
 
        model.addAttribute("c", c);
        return "fore/category";
    }

	@RequestMapping("foresearch")
    public String search( String keyword,Model model){
 
        PageHelper.offsetPage(0,20);
        List<Product> ps= productService.search(keyword);
        productService.setSaleAndReviewNumber(ps);
        model.addAttribute("ps",ps);
        return "fore/searchResult";
    }
	
	
	/**
	 * 立即购买
	 * @param pid
	 * @param num
	 * @param session
	 * @return
	 */
	@RequestMapping("forebuyone")
    public String buyone(int pid, int num, HttpSession session) {
        Product p = productService.get(pid);
        int oiid = 0;
 
        User user =(User)  session.getAttribute("user");
        boolean found = false;
        List<Orderitem> ois = orderItemService.listByUserAndOidIsNull(user.getId());
        for (Orderitem oi : ois) {
            if(oi.getProduct().getId().intValue()==p.getId().intValue()){
                oi.setNumber(oi.getNumber()+num);
                orderItemService.update(oi);
                found = true;
                oiid = oi.getId();
                break;
            }
        }
 
        if(!found){
            Orderitem oi = new Orderitem();
            oi.setUid(user.getId());
            oi.setNumber(num);
            oi.setPid(pid);
            orderItemService.add(oi);
            oiid = oi.getId();
        }
        return "redirect:forebuy?oiid="+oiid;
    }
	
	
	/**
	 * 结算页面
	 * @param model
	 * @param oiid
	 * @param session
	 * @return
	 */
	@RequestMapping("forebuy")
    public String buy( Model model,String[] oiid,HttpSession session){
        List<Orderitem> ois = new ArrayList<>();
        float total = 0;
 
        for (String strid : oiid) {
            int id = Integer.parseInt(strid);
            Orderitem oi= orderItemService.get(id);
            total +=oi.getProduct().getPromoteprice()*oi.getNumber();
            ois.add(oi);
        }
 
        session.setAttribute("ois", ois);
        model.addAttribute("total", total);
        return "fore/buy";
    }
 
	/**
	 * 添加到购物车
	 * @param pid
	 * @param num
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("foreaddCart")
    @ResponseBody
    public String addCart(int pid, int num, Model model,HttpSession session) {
        Product p = productService.get(pid);
        User user =(User)  session.getAttribute("user");
        boolean found = false;
 
        List<Orderitem> ois = orderItemService.listByUserAndOidIsNull(user.getId());
        for (Orderitem oi : ois) {
            if(oi.getProduct().getId().intValue()==p.getId().intValue()){
                oi.setNumber(oi.getNumber()+num);
                orderItemService.update(oi);
                found = true;
                break;
            }
        }
 
        if(!found){
        	Orderitem oi = new Orderitem();
            oi.setUid(user.getId());
            oi.setNumber(num);
            oi.setPid(pid);
            orderItemService.add(oi);
        }
        return "success";
    }
	
	/**
	 * 查看购物车
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("forecart")
    public String cart( Model model,HttpSession session) {
        User user =(User)  session.getAttribute("user");
        List<Orderitem> ois = orderItemService.listByUserAndOidIsNull(user.getId());
        model.addAttribute("ois", ois);
        return "fore/cart";
    }
 
	/**
	 * 生成订单
	 * @param model
	 * @param order
	 * @param session
	 * @return
	 */
	@RequestMapping("forecreateOrder")
	public String createOrder( Model model,Order order,HttpSession session){
	    User user =(User)  session.getAttribute("user");
	    String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000);
	    order.setOrdercode(orderCode);
	    order.setCreatedate(new Date());
	    order.setUid(user.getId());
	    order.setStatus(OrderService.waitPay);
	    List<Orderitem> ois= (List<Orderitem>)  session.getAttribute("ois");
	 
	    float total =orderService.add(order,ois);
	    return "redirect:forealipay?oid="+order.getId() +"&total="+total;
	}
	
	/**
	 * 支付成功
	 * @param oid
	 * @param total
	 * @param model
	 * @return
	 */
	@RequestMapping("forepayed")
	public String payed(int oid, float total, Model model) {
	    Order order = orderService.get(oid);
	    order.setStatus(OrderService.waitDelivery);
	    order.setPaydate(new Date());
	    orderService.update(order);
	    model.addAttribute("o", order);
	    return "fore/payed";
	}
	
	
	/**
	 * 查看已购买的商品
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("forebought")
    public String bought( Model model,HttpSession session) {
        User user =(User)  session.getAttribute("user");
        List<Order> os= orderService.listByUidAndNotDelete(user.getId());
 
        orderItemService.fill(os);
 
        model.addAttribute("os", os);
 
        return "fore/bought";
    }
 
 
	/**
	 * 确认收货页面
	 * @param model
	 * @param oid
	 * @return
	 */
	@RequestMapping("foreconfirmPay")
	public String confirmPay( Model model,int oid) {
	    Order o = orderService.get(oid);
	    orderItemService.fill(o);
	    model.addAttribute("o", o);
	    return "fore/confirmPay";
	}
	
	
	/**
	 * 确认收货
	 * @param model
	 * @param oid
	 * @return
	 */
	@RequestMapping("foreorderConfirmed")
	public String orderConfirmed( Model model,int oid) {
	    Order o = orderService.get(oid);
	    o.setStatus(OrderService.waitReview);
	    o.setConfirmdate(new Date());
	    orderService.update(o);
	    return "fore/orderConfirmed";
	}
	
	/**
	 * 删除订单
	 * @param model
	 * @param oid
	 * @return
	 */
	@RequestMapping("foredeleteOrder")
    @ResponseBody
    public String deleteOrder( Model model,int oid){
        Order o = orderService.get(oid);
        o.setStatus(OrderService.delete);
        orderService.update(o);
        return "success";
    }
	
	/**
	 * 评价页初始化
	 * @param model
	 * @param oid
	 * @return
	 */
	@RequestMapping("forereview")
	public String review( Model model,int oid) {
	    Order o = orderService.get(oid);
	    orderItemService.fill(o);
	    Product p = o.getOrderItems().get(0).getProduct();
	    List<Review> reviews = reviewService.list(p.getId());
	    productService.setSaleAndReviewNumber(p);
	    model.addAttribute("p", p);
	    model.addAttribute("o", o);
	    model.addAttribute("reviews", reviews);
	    return "fore/review";
	}
	
	/**
	 * 提交评价
	 * @param model
	 * @param session
	 * @param oid
	 * @param pid
	 * @param content
	 * @return
	 */
	@RequestMapping("foredoreview")
	public String doreview( Model model,HttpSession session,int oid,int pid,String content) {
	    Order o = orderService.get(oid);
	    o.setStatus(OrderService.finish);
	    orderService.update(o);
	 
	    Product p = productService.get(pid);
	    content = HtmlUtils.htmlEscape(content);
	 
	    User user =(User)  session.getAttribute("user");
	    Review review = new Review();
	    review.setContent(content);
	    review.setPid(pid);
	    review.setCreatedate(new Date());
	    review.setUid(user.getId());
	    reviewService.add(review);
	 
	    return "redirect:forereview?oid="+oid+"&showonly=true";
	}
}
